/*
 * Copyright (c) 2010, Lauren Darcey and Shane Conder
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are 
 * permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this list of 
 *   conditions and the following disclaimer.
 *   
 * * Redistributions in binary form must reproduce the above copyright notice, this list 
 *   of conditions and the following disclaimer in the documentation and/or other 
 *   materials provided with the distribution.
 *   
 * * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used
 *   to endorse or promote products derived from this software without specific prior 
 *   written permission.
 *   
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * <ORGANIZATION> = Mamlambo
 */
package com.mamlambo.articles.openglesprimer;

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.app.Activity;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.os.Bundle;
import android.view.KeyEvent;

public class QuickLitCubeActivity extends Activity {
    CustomSurfaceView mAndroidSurface = null;

    @Override
    protected void onPause() {
        super.onPause();
        if (mAndroidSurface != null) {
            mAndroidSurface.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAndroidSurface != null) {
            mAndroidSurface.onResume();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAndroidSurface = new CustomSurfaceView(this);
        setContentView(mAndroidSurface);
    }

    private class CustomSurfaceView extends GLSurfaceView {
        final CustomRenderer mRenderer = new CustomRenderer();

        public CustomSurfaceView(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);
            // request OpenGL ES 1.x (so we have a fixed shader pipeline)
            // NOTE: ES 1.x and ES 2.0 are not compatible.
            setEGLContextClientVersion(1);
            setRenderer(mRenderer);
        }

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_P:
                queueEvent(new Runnable() {
                    public void run() {
                        mRenderer.togglePause();
                    }
                });
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    }

    private class CustomRenderer implements GLSurfaceView.Renderer {

        @SuppressWarnings("unused")
        private static final String DEBUG_TAG = "ShowAndroidGLActivity$CustomRenderer";

        boolean fAnimPaused = false;
        float mRotateAngle = 0f;
        
        public void onDrawFrame(GL10 gl) {
            if (fAnimPaused) {
                return;
            }

            gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

            gl.glMatrixMode(GL10.GL_MODELVIEW);
            gl.glLoadIdentity();
                       
            // draw a red cube
            // draws 5 to the right of center, spinning about its x axis
            gl.glTranslatef(5f, 0f, 0f);
            gl.glRotatef(mRotateAngle,  1f, 0f, 0f);
            gl.glColor4f(1f, 0f, 0f, 1f);
            quickCube.draw(gl);
            
            gl.glLoadIdentity();
            
            // draw a green cube
            // draws 5 towards the viewer, spinning around all axis
            gl.glTranslatef(0f, 0f, 5f);
            gl.glRotatef(mRotateAngle, 1f, 1f, 1f);
            

            gl.glColor4f(0f, 1f, 0f, 1f);
            quickCube.drawAgain(gl);

            // draw a blue cube
            // draws up 5, spinning around its z axis
            gl.glLoadIdentity();
            
            gl.glTranslatef(0f, 5f, 0f);
            gl.glRotatef(mRotateAngle, 0f, 0f, 1f);
            
            gl.glColor4f(0f, 0f, 1f, 1f);
            quickCube.drawAgain(gl);
            
            
            // draw a yellow cube
            // draws down 5, spinning around its y axis
            gl.glLoadIdentity();
            
            gl.glTranslatef(0f, -5f, 0f);
            gl.glRotatef(mRotateAngle, 0f, 1f, 0f);
            
            gl.glColor4f(1f, 0.5f, 0f, 1f);
            quickCube.drawAgain(gl);
            
            // draw another red cube
            // draws to the left 5, spinning around its x axis
            gl.glLoadIdentity();
            
            gl.glTranslatef(-5f, 0f, 0f);
            gl.glRotatef(mRotateAngle, 1f, 0f, 0f);
            
            gl.glColor4f(1f, 0f, 0f, 1f);
            quickCube.drawAgain(gl);
            
            // draw a light blue cube
            // 7 away from the origin, orbiting around the origin at a 45 degree angle
            // getting closer to the viewer, then farther away. passes in front of the green
            // cube. cube is drawn half size
            gl.glLoadIdentity();
            
            //gl.glRotatef(mRotateAngle, 1f, 0f, 0f);
            gl.glRotatef(45f, 0f, 0f, 1f);
            gl.glRotatef(mRotateAngle*3, 0f, 1f, 0f);
            
            gl.glTranslatef(-7f, 0f, 0f);
            gl.glScalef(0.5f, 0.5f, 0.5f);
            
            
            gl.glColor4f(0f, 0.5f, 1f, 1f);
            quickCube.drawAgain(gl);
            
            mRotateAngle += 0.5f;
        }

        public void togglePause() {
            if (fAnimPaused == true) {
                fAnimPaused = false;
            } else {
                fAnimPaused = true;
            }
        }

        public void onSurfaceChanged(GL10 gl, int width, int height) {
            gl.glViewport(0, 0, width, height);

            float ratio = (float) width / height;
            gl.glMatrixMode(GL10.GL_PROJECTION);
            gl.glLoadIdentity();
            // a common way to set the aspect ratio properly
            gl.glFrustumf(-ratio, ratio, -1, 1, 1, 50);
            GLU.gluLookAt(gl, 0, 0, 12f, 0, 0, 0, 0, 1, 0f);

            // enable lighting
            gl.glEnable(GL10.GL_LIGHTING);

            // turn on the first light
            gl.glEnable(GL10.GL_LIGHT0);

            // put some dim ambient light on the scene
            gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, new float[] { 0.1f,
                    0.1f, 0.1f, 1f }, 0);

            // light that reflects in all directions
            gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, new float[] { 1f, 1f,
                    1f, 1f }, 0);

            // location of the light within the projection/eye space
            gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, new float[] { 10f,
                    10f, 10f, 1 }, 0);

            // the drawing color becomes the lit material color with this on
            gl.glEnable(GL10.GL_COLOR_MATERIAL);
        }

        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            // one-time initialization; items that don't change when the surface
            // metrics change
            // all drawing uses a vertex array (and it does)
            gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);            
            gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
            gl.glDisable(GL10.GL_DITHER);
            gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
            gl.glClearColor(0.7f, 0.7f, 0.7f, 1);
            gl.glShadeModel(GL10.GL_SMOOTH);
            gl.glEnable(GL10.GL_DEPTH_TEST);
            // for lighting, we must use proper surface normals
            // with proper surface normals, face culling works properly, too
            gl.glEnable(GL10.GL_CULL_FACE);
            
            // initialize the cube class
            quickCube = new QuickCube(2f); 
        }
        QuickCube quickCube;

        // a "real" cube implementation
        public class QuickCube  {

            private float mSize;
            
            private FloatBuffer mVertexBuffer;
            private FloatBuffer mNormalBuffer;
            private ByteBuffer mIndexBuffer;
            
            QuickCube(float size) throws IllegalArgumentException {
                if (size < 0.0f) {
                    throw new IllegalArgumentException("Only use positive size values to CubeSmallGLUT");
                }
                
                // scale unit cube to this size
                mSize = size;
                
                if (mSize != 1.0f) {
                    for (int vertex = 0; vertex < vertices.length; vertex++ ) {
                        vertices[vertex] *= mSize;
                    }
                }
                
                mVertexBuffer = OpenGLUtilities.getFloatBufferFromFloatArray(vertices);
                mNormalBuffer = OpenGLUtilities.getFloatBufferFromFloatArray(normals);
                mIndexBuffer = OpenGLUtilities.getByteBufferFromByteArray(indices);
            }
            
            // center our unit cube around the origin so translations make sense
            float vertices[] = {
                // front
                -0.5f, 0.5f, 0.5f,   0.5f, 0.5f, 0.5f,   0.5f,-0.5f, 0.5f,  -0.5f,-0.5f, 0.5f,
                
                // back
                 0.5f, 0.5f,-0.5f,  -0.5f, 0.5f,-0.5f,  -0.5f,-0.5f,-0.5f,   0.5f,-0.5f,-0.5f,
                
                // top
                -0.5f, 0.5f,-0.5f,   0.5f, 0.5f,-0.5f,   0.5f, 0.5f, 0.5f,  -0.5f, 0.5f, 0.5f,
                
                // bottom
                -0.5f,-0.5f, 0.5f,   0.5f,-0.5f, 0.5f,   0.5f,-0.5f,-0.5f,  -0.5f,-0.5f,-0.5f,
                
                // right
                 0.5f, 0.5f, 0.5f,   0.5f, 0.5f,-0.5f,   0.5f,-0.5f,-0.5f,   0.5f,-0.5f, 0.5f,
                 
                // left
                -0.5f, 0.5f,-0.5f, -0.5f, 0.5f, 0.5f,  -0.5f,-0.5f, 0.5f,  -0.5f,-0.5f,-0.5f,
            };
            
            byte indices[] = {
                //front
                0,1,2, 2,3,0,
                //back
                4,5,6, 6,7,4,
                // top
                8,9,10, 10,11,8,
                // bottom
                12,13,14,  14,15,12,
                //right
                16,17,18,  18,19,16,
                //left
                20,21,22,  22,23,20,
            };
            
            float normals[] = {
            // front
                    0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
                    // back
                    0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1,
                    // top
                    0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
                    // bottom
                    0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,
                    // right
                    1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
                    // left
                    -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, };
            
            
            void draw(GL10 gl) {
                // needed for correct culling, our vertices are clockwise
                gl.glFrontFace(GL10.GL_CW);

                // set our vertexes
                gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);

                // set our normals for correct lighting
                gl.glNormalPointer(GL10.GL_FLOAT, 0, mNormalBuffer);

                // draw the elements
                gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
                        GL10.GL_UNSIGNED_BYTE, mIndexBuffer);

            }
            
            void drawAgain(GL10 gl) {
                // used to draw again when the vertex and normal pointers haven't changed -- won't work otherwise
            
                // draw the elements -- assuming all of the above prep has taken place
                gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_BYTE, mIndexBuffer);
            }
        }
        
    }
}
